package com.gmail.bogatyr.alexander.server.guice;

import com.gmail.bogatyr.alexander.server.dao.ITelephoneBookDao;
import com.gmail.bogatyr.alexander.server.dao.TelephoneBookDao;
import com.gmail.bogatyr.alexander.server.manager.TelephoneBookManager;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class HibernateModule extends AbstractModule {

    private static final ThreadLocal<EntityManager> ENTITY_MANAGER_CACHE = new ThreadLocal<>();

    public void configure() {
        bind(ITelephoneBookDao.class).to(TelephoneBookDao.class);
    }

    @Provides
    @Singleton
    public EntityManagerFactory provideEntityManagerFactory() {
        return Persistence.createEntityManagerFactory("telephonebook-db");
    }

    @Provides
    public EntityManager provideEntityManager(EntityManagerFactory entityManagerFactory) {
        EntityManager entityManager = ENTITY_MANAGER_CACHE.get();
        if (entityManager == null) {
            entityManager = entityManagerFactory.createEntityManager();
            ENTITY_MANAGER_CACHE.set(entityManager);
        }
        return entityManager;
    }
}
